<template>
  <div class="search">
    <van-nav-bar left-arrow title="商品搜索" @click-left="$router.back()" />
    <van-search
      ref="search"
      v-model="search"
      placeholder="请输入您搜索的商品"
      show-action
      @search="onSearch"
    >
      <template #action>
        <div class="btn" @click="onSearch(search)">搜索</div>
      </template>
    </van-search>
    <div class="content">
      <div class="con">
        <div class="con-left">最近搜索</div>
        <div class="con-right">
          <van-icon name="delete-o" @click="clear" />
        </div>
      </div>
      <div class="con-box">
        <div
          v-for="(item, index) in searchData"
          :key="index"
          class="con-data"
          @click="onSearch(item)"
        >
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getHistoryList, setHistoryList } from '@/utils/storage'

export default {
  name: 'searchCom',
  components: {},
  data () {
    return {
      searchData: getHistoryList(),
      search: ''
    }
  },
  computed: {},
  mounted () {
    this.$nextTick(() => {
      this.$refs.search.querySelector('input').focus()
    })
  },
  methods: {
    onSearch (key) {
      if (key === '') {
        this.$router.push('/searchList')
      } else {
        const index = this.searchData.indexOf(key)
        if (index !== -1) {
          this.searchData.splice(index, 1)
        }
        this.searchData.unshift(key)
        setHistoryList(this.searchData)
        this.$router.push(`/searchList?search=${key}`)
      }
    },
    clear () {
      this.searchData = []
      setHistoryList([])
      this.$toast.success('清空历史成功')
    }
  },
  created () {}
}
</script>
<style lang="less">
.search {
  .btn {
    width: 80px;
    line-height: 33px;
    text-align: center;
    margin-left: -10px;
    background-color: #fa2209;
    color: #ffffff;
    border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
  }

  .content {
    padding: 20px;

    .con {
      display: flex;
      justify-content: space-between;
      font-size: 15px;

      .con-left {
        color: #80828a;
      }
    }

    .con-box {
      display: flex;
      flex-wrap: wrap;

      .con-data {
        width: 100px;
        line-height: 30px;
        border: 1px solid #80828a;
        margin-top: 20px;
        border-radius: 10px;
        text-align: center;
        margin-left: 10px;
        margin-bottom: 10px;
      }
    }
  }
}
</style>
